package com.example.swd1.gudong.main.user.myinfo;

import android.app.AlertDialog;
import android.content.ContentResolver;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;

import com.example.swd1.gudong.R;
import com.example.swd1.gudong.main.user.myinfo.fragment.MyDetailsFragment;
import com.example.swd1.gudong.main.user.myinfo.fragment.MySportRangFragment;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

//==================================================================================================================
//   Author :  Shile Wu
//   Date  :  16-8-19
//   Role :    xx
//   Reference documents : xx
//==================================================================================================================
public class MyInfoActivity extends AppCompatActivity implements View.OnClickListener, ViewPager.OnPageChangeListener {
    private static final int TAKE_PHOTO = 0;
    private static final int CROP_PHOTO = 1;
    private LinearLayout ll_myinfo_detail;
    private TextView tv_myinfo_detail_text;
    private TextView tv_myinfo_detail_link;
    private LinearLayout ll_myinfo_sportrang;
    private TextView tv_myinfo_sportrang_text;
    private TextView tv_myinfo_sportrang_link;
    private ImageView iv_myinfo_background;
    private TextView tv_myinfo_camera;
    private TextView tv_myinfo_album;
    private ScrollView sv_myinfo;
    private ImageView iv_info_head;
    private RelativeLayout rl_myinfo_head;
    private ImageView iv_myinfo_back;
    private AlertDialog dialog;
    private boolean isDetailChoose;//current view page flag
    private int greenColor;
    private int whiteColor;
    private int grayColor;
    private View dialogView;
    private ViewPager vp_info_detail;
    List<Fragment> fragments;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_myinfo);
        iv_myinfo_background = (ImageView) findViewById(R.id.iv_myinfo_background);
        vp_info_detail = (ViewPager) findViewById(R.id.vp_info_detail);
        ll_myinfo_detail = (LinearLayout) findViewById(R.id.ll_myinfo_detail);
        tv_myinfo_detail_text = (TextView) findViewById(R.id.tv_myinfo_detail_text);
        tv_myinfo_detail_link = (TextView) findViewById(R.id.tv_myinfo_detail_link);
        ll_myinfo_sportrang = (LinearLayout) findViewById(R.id.ll_myinfo_sportrang);
        tv_myinfo_sportrang_text = (TextView) findViewById(R.id.tv_myinfo_sportrang_text);
        tv_myinfo_sportrang_link = (TextView) findViewById(R.id.tv_myinfo_sportrang_link);
        sv_myinfo = (ScrollView) findViewById(R.id.sv_myinfo);
        rl_myinfo_head = (RelativeLayout) findViewById(R.id.rl_myinfo_head);
        iv_myinfo_back = (ImageView) findViewById(R.id.iv_myinfo_back);
        iv_info_head = (ImageView) findViewById(R.id.iv_info_head);

        ll_myinfo_detail.setOnClickListener(this);
        ll_myinfo_sportrang.setOnClickListener(this);
        iv_myinfo_background.setOnClickListener(this);

        initDialog();
        initColor();
        intUI();

        rl_myinfo_head.setAlpha(0F);
        iv_myinfo_back.setOnClickListener(this);
        sv_myinfo.setOnScrollChangeListener(scrollChangeListener);
    }

    private void initDialog() {
        dialogView = View.inflate(MyInfoActivity.this, R.layout.dialog_choose_background, null);
        tv_myinfo_camera = (TextView) dialogView.findViewById(R.id.tv_myinfo_camera);
        tv_myinfo_album = (TextView) dialogView.findViewById(R.id.tv_myinfo_album);
        tv_myinfo_camera.setOnClickListener(this);
        tv_myinfo_album.setOnClickListener(this);
        dialog = new AlertDialog.Builder(MyInfoActivity.this)
                .setView(dialogView).create();
    }

    private void intUI() {
        //Init icon
        Bitmap headBitmap = BitmapFactory.decodeFile(getFilesDir().getAbsolutePath() + "/" + getString(R.string.user_head_name));
        if (headBitmap != null) {
            displayBitmap(headBitmap);
        }

        //Init ViewPage
        MyDetailsFragment myDetailsFragment = new MyDetailsFragment();
        MySportRangFragment mySportRangFragment = new MySportRangFragment();

        fragments = new ArrayList<>();
        fragments.add(myDetailsFragment);
        fragments.add(mySportRangFragment);

        MyInfoViewPageAdapter myInfoViewPageAdapter = new MyInfoViewPageAdapter(getSupportFragmentManager(), fragments);
        vp_info_detail.setAdapter(myInfoViewPageAdapter);
        vp_info_detail.setOnPageChangeListener(this);
    }

    private void initColor() {
        greenColor = getResources().getColor(R.color.text_link);
        whiteColor = getResources().getColor(android.R.color.white);
        grayColor = getResources().getColor(R.color.sticker_edit_text_hint_color);
    }


    public void switchChoose() {
        if (isDetailChoose) {
            setDetailChoose();
        } else {
            setSportRangChoose();
        }
    }

    private void setDetailChoose() {
        tv_myinfo_detail_text.setTextColor(greenColor);
        tv_myinfo_detail_link.setBackgroundColor(greenColor);
        tv_myinfo_sportrang_text.setTextColor(grayColor);
        tv_myinfo_sportrang_link.setBackgroundColor(whiteColor);
    }

    private void setSportRangChoose() {
        tv_myinfo_detail_text.setTextColor(grayColor);
        tv_myinfo_detail_link.setBackgroundColor(whiteColor);
        tv_myinfo_sportrang_text.setTextColor(greenColor);
        tv_myinfo_sportrang_link.setBackgroundColor(greenColor);
    }


    @Override
    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

    }

    @Override
    public void onPageSelected(int position) {
        switch (position) {
            case 0:
                isDetailChoose = true;
                switchChoose();
                break;
            case 1:
                isDetailChoose = false;
                switchChoose();
                break;
            default:
                break;
        }
    }

    @Override
    public void onPageScrollStateChanged(int state) {

    }

    @Override
    public void onClick(View v) {
        if (v == ll_myinfo_detail) {
            vp_info_detail.setCurrentItem(0);
            return;
        }
        if (v == ll_myinfo_sportrang) {
            vp_info_detail.setCurrentItem(1);
            return;
        }
        if (v == iv_myinfo_background) {
            dialog.show();
            return;
        }
        if (v == tv_myinfo_camera) {
            dialog.dismiss();
            Intent intent = new Intent();
            intent.setAction(MediaStore.ACTION_IMAGE_CAPTURE);
            //Cache image in SDCard
            Uri imageUri = Uri.fromFile(new File(Environment.getExternalStorageDirectory(), "image.png"));
            intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
            startActivityForResult(intent, TAKE_PHOTO);
            return;
        }
        if (v == tv_myinfo_album) {
            dialog.dismiss();
            Intent intent = new Intent();
            intent.setAction(Intent.ACTION_GET_CONTENT);
            intent.setType("image/*");
            startActivityForResult(intent, CROP_PHOTO);
            return;
        }
        if (v == iv_myinfo_back) {
            finish();
            return;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        Bitmap bitmap = null;
        switch (requestCode) {
            case TAKE_PHOTO:
                File image = new File(Environment.getExternalStorageDirectory() + "/image.png");
                bitmap = BitmapFactory.decodeFile(image.getAbsolutePath());
                //if don't have storage permission , will occur NullPointException
                if(bitmap==null) {
                    Toast.makeText(this,"Please open storage permission!",Toast.LENGTH_LONG).show();
                    return;
                }
                image.delete();
                break;
            case CROP_PHOTO:
                ContentResolver contentResolver = getContentResolver();
                Uri imageUri = data.getData();
                try {
                    bitmap = MediaStore.Images.Media.getBitmap(contentResolver, imageUri);
                } catch (IOException e) {
                    e.printStackTrace();
                }
                break;
        }
        Bitmap hBitmap = resizeBitmap(bitmap, 100);
        saveBitmap(hBitmap);
        displayBitmap(hBitmap);
    }

    private void saveBitmap(Bitmap bitmap) {
        //Save bitmap
        try {
            FileOutputStream fos = openFileOutput(getString(R.string.user_head_name), MODE_PRIVATE);
            bitmap.compress(Bitmap.CompressFormat.PNG, 90, fos);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        displayBitmap(bitmap);

    }

    private void displayBitmap(Bitmap bitmap) {
        //Show bitmap
        iv_info_head.setImageBitmap(bitmap);
    }

    private View.OnScrollChangeListener scrollChangeListener = new View.OnScrollChangeListener() {

        @Override
        public void onScrollChange(View v, int scrollX, int scrollY, int oldScrollX, int oldScrollY) {
            Log.i("TAG", "MyInfoActivity onScrollChange() Y: " + scrollY);
            if (scrollY < 20) {
                iv_myinfo_back.setImageResource(R.drawable.uui_back);
                Log.i("TAG", "<60");
                rl_myinfo_head.setAlpha(0F);
                iv_myinfo_back.setAlpha(1F);
            } else if (scrollY < 40) {
                Log.i("TAG", "<120");
                rl_myinfo_head.setAlpha(0.1F);
                iv_myinfo_back.setAlpha(0.875F);
            } else if (scrollY < 60) {
                Log.i("TAG", "<120");
                rl_myinfo_head.setAlpha(0.15F);
                iv_myinfo_back.setAlpha(0.75F);
            } else if (scrollY < 80) {
                Log.i("TAG", "<120");
                rl_myinfo_head.setAlpha(0.2F);
                iv_myinfo_back.setAlpha(0.625F);
            } else if (scrollY < 100) {
                Log.i("TAG", "<120");
                rl_myinfo_head.setAlpha(0.25F);
                iv_myinfo_back.setAlpha(0.3F);

            } else if (scrollY < 120) {
                Log.i("TAG", "<120");
                iv_myinfo_back.setImageResource(R.drawable.uui_back_grey);
                rl_myinfo_head.setAlpha(0.2F);
            } else if (scrollY < 150) {
                Log.i("TAG", "<180");
                rl_myinfo_head.setAlpha(0.4F);
                iv_myinfo_back.setAlpha(0.3F);
            } else if (scrollY < 180) {
                Log.i("TAG", "<240");
                rl_myinfo_head.setAlpha(0.5F);
                iv_myinfo_back.setAlpha(0.5F);
            } else if (scrollY < 210) {
                Log.i("TAG", "<300");
                rl_myinfo_head.setAlpha(0.6F);
                iv_myinfo_back.setAlpha(0.6F);
            } else if (scrollY < 240) {
                Log.i("TAG", "<300");
                rl_myinfo_head.setAlpha(0.7F);
                iv_myinfo_back.setAlpha(0.7F);
            } else if (scrollY < 270) {
                Log.i("TAG", "<300");
                rl_myinfo_head.setAlpha(0.8F);
                iv_myinfo_back.setAlpha(0.8F);
            } else if (scrollY < 300) {
                Log.i("TAG", "<300");
                rl_myinfo_head.setAlpha(0.9F);
                iv_myinfo_back.setAlpha(0.9F);
            } else {
                rl_myinfo_head.setAlpha(1F);
                iv_myinfo_back.setAlpha(1F);
            }
        }
    };

    public Bitmap resizeBitmap(Bitmap bitmap, int newWidth) {
        int width = bitmap.getWidth();
        int height = bitmap.getHeight();
        float temp = ((float) height) / ((float) width);
        int newHeight = (int) ((newWidth) * temp);
        float scaleWidth = ((float) newWidth) / width;
        float scaleHeight = ((float) newHeight) / height;
        Matrix matrix = new Matrix();
        // resize the bit map
        matrix.postScale(scaleWidth, scaleHeight);
        // matrix.postRotate(45);
        Bitmap resizedBitmap = Bitmap.createBitmap(bitmap, 0, 0, width, height, matrix, true);
        bitmap.recycle();
        return resizedBitmap;
    }
}
